<template>
	<view class="container">
		
		<!-- 地图容器 -->
		<map 
			id="map"
			:latitude="center.latitude" 
			:longitude="center.longitude"
			:markers="markers" 
			:include-points="includePoints"
			:polyline="polyline" 
			scale="12"
			v-if="polyline[0].points.length"
			show-location
		>
		</map>
		<view id="map" v-else></view>
		
		<!--订单卡片-->
		<view class="box">
			<view class="head">
				<view class="avatar">
					<image :src="getUserAvatarOrDefault(info.avatar)" alt="avatar" />
				</view>
				<view class="center">
					<view class="username">
						{{ info.username }}
					</view>
					<view class="xcx">
						小程序
					</view>
				</view>
				<view class="call" @tap="callClient">
					<!-- <a href="tel:13415817803">Call Now</a> -->
					<uni-icons type="phone" size="26" color="#19afff"></uni-icons>
				</view>
			</view>
			<view class="tags">
				<view>
					实时
				</view>
				<view>
					里程模式
				</view>
				<view>
					{{ [orderTypeEnum.WAIT.code, orderTypeEnum.GET.code].includes(info.status) ? '距您' : '总里程' }}:{{ distance }}km
				</view>
				<view class="price" v-if="orderTypeEnum.FINISH.code !== info.status">
					<text>预计: </text>
					<text class="num">{{ formatAmount(info.price) }}</text>
					<text>(元)</text>
				</view>
			</view>
			<view class="from-and-to">
				<view class="from">
					<view class="left">
						<view class="dot green"></view>
						<view class="text">起点：{{ info.currentAddr }}</view>
					</view>
					<view class="right" @tap="handlerGotoAddr('start')">
						<text>导航</text>
						<uni-icons type="right" color="#19afff"></uni-icons>
					</view>
				</view>
				<view class="to">
					<view class="left">
						<view class="dot red"></view>
						<view class="text">终点：{{ info.targetAddr }}</view>
					</view>
					<view class="right" @tap="handlerGotoAddr('end')">
						<text>导航</text>
						<uni-icons type="right" color="#19afff"></uni-icons>
					</view>
				</view>
			</view>
			<view class="time">
				<view>
					订单号：{{ info.id }}
				</view>
				<view>
					下单时间：{{ formatDatetime(info.orderTime) }}
				</view>
				<view>
					出发时间：{{ formatDatetime(info.hopeTime) }}
				</view>
				<view v-if="[orderTypeEnum.PENDING_PAY.code, orderTypeEnum.FINISH.code].includes(info.status) && info.endTime">
					到达时间：{{ formatDatetime(info.endTime) }}
				</view>
			</view>
			<!--按钮-->
			<view class="btn-contanier">
				<view class="btn primary-btn" @tap="handlerGrabOrder" v-if="orderTypeEnum.WAIT.code === info.status">
					迅速抢单
				</view>
				
				<view 
					class="btn-goto primary-btn" 
					v-if="[orderTypeEnum.GET.code, orderTypeEnum.WAITING.code, orderTypeEnum.START.code].includes(info.status)"
					@tap="handlerUpdateOrderStatus(info.status + 1, status2text(info.status))"
				>
					{{ status2text(info.status) }}
				</view>
			</view>
		</view>
		
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { orderTypeEnum } from '@/utils/orderType.js'
import { getOrderById, updateStatus, finishOrder } from '@/api/order.js'
import { formatDatetime } from '@/utils/datetimeUtil.js'
import { grabOrder } from '@/api/order.js'
import { formatAmount } from '@/utils/amountUtil.js'
import { getUserAvatarOrDefault } from '@/utils/imageUtil.js'

// 地图中心点
const center = ref({
	latitude: 39.906036,
	longitude: 116.397697
})

// 标记点
const markers = ref([])
// 包含点
const includePoints = ref([])
// 路线
const polyline = ref([{
	points: [],
	color: '#0ebd31',
	width: 5,
	borderWidth: 3,
	borderColor: '#FFFFFF',
	dottedLine: true,
	arrowLine: true // 带箭头的线
}])

// 订单信息
const info = ref({
	id: null,
	businessType: null,
	currentLo: null,
	currentLa: null,
	currentAddr: null,
	targetLo: null,
	targetLa: null,
	targetAddr: null,
	orderTime: null,
	hopeTime: null,
	receiveTime: null,
	reachTime: null,
	startTime: null,
	endTime: null,
	price: null,
	userId: null,
	username: null,
	avatar: null,
	userPhone: null,
	status: null,
	remark: null,
	driverId: null,
	driverAge: null,
	surname: null,
	name: null,
	driverPhone: null,
	driverStatus: null
})

// 路程距离
const distance = ref(0)

/** 根据状态返回文字 */
function status2text (status) {
	switch (status) {
		case orderTypeEnum.GET.code:
			return '开始等待'
		case orderTypeEnum.WAITING.code:
			return '开始服务'
		case orderTypeEnum.START.code:
			return '完成订单'
	}
}
// 获取定位
function getCurrLocation () {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			mask: true,
			title: '获取定位中...'
		})
		uni.getLocation({
			isHighAccuracy: true,
			success: (res) => {
				uni.hideLoading()
				const { latitude, longitude } = res
				center.value.latitude = latitude
				center.value.longitude = longitude
				resolve()
			},
			fail: (err) => {
				uni.hideLoading()
				uni.showToast({
					icon: 'none',
					title: '获取定位失败'
				})
				reject()
			}
		})
	})
}
// 构造一个marker
function buildOneMarker (latitude, longitude, title, iconPath) {
	return {
		id: new Date().getTime(),
		latitude,
		longitude,
		title,
		iconPath,
		width: 24,
		height: 24,
		anchor: {
			x: 0.5,
			y: 1
		},
		joinCluster: true
	}
}
// 初始化markers
function initMarkers () {
	markers.value.push(buildOneMarker(info.value.currentLa, info.value.currentLo, info.value.currentAddr, '/static/location-green.png'))
	markers.value.push(buildOneMarker(info.value.targetLa, info.value.targetLo, info.value.targetAddr, '/static/location-red.png'))
	
	if ([orderTypeEnum.WAIT.code, orderTypeEnum.GET.code].includes(info.value.status)) {
		includePoints.value.push(buildOneMarker(center.value.latitude, center.value.longitude, '您的位置', undefined))
		includePoints.value.push(buildOneMarker(info.value.currentLa, info.value.currentLo, info.value.currentAddr, '/static/location-green.png'))
	} else {
		includePoints.value.push(buildOneMarker(info.value.currentLa, info.value.currentLo, info.value.currentAddr, '/static/location-green.png'))
		includePoints.value.push(buildOneMarker(info.value.targetLa, info.value.targetLo, info.value.targetAddr, '/static/location-red.png'))
	}
}
// 初始化路线
function initPolyline () {
	let origin = ''
	let destination = ''
	if ([orderTypeEnum.WAIT.code, orderTypeEnum.GET.code].includes(info.value.status)) {
		origin = `${center.value.longitude},${center.value.latitude}`
		destination = `${info.value.currentLo},${info.value.currentLa}`
	} else {
		origin = `${info.value.currentLo},${info.value.currentLa}`
		destination = `${info.value.targetLo},${info.value.targetLa}`
	}
	
	uni.request({
		url: 'https://restapi.amap.com/v5/direction/driving',
		method: 'GET',
		data: {
			key: '9996b2ae4c2bd5c1caab3861243bb047',
			origin,
			destination,
			show_fields: 'polyline',
			strategy: 2
		}
	}).then(res => {
		distance.value = ( res.data.route.paths[0].distance / 1000 ).toFixed(2)
		
		const polynineArray = []
		const path = res.data.route.paths[0]
		for (const step of path.steps) {
			const lonlats = step.polyline.split(';')
			for (const lonlat of lonlats) {
				const lon = lonlat.split(',')[0]
				const lat = lonlat.split(',')[1]
				polynineArray.push({ latitude: lat, longitude: lon })
			}
		}
		polyline.value[0].points = polynineArray
	})
}

/** 呼叫用户 */
function callClient () {
	uni.makePhoneCall({
		phoneNumber: info.value.userPhone
	})
}

/** 抢单 */
function handlerGrabOrder () {
	grabOrder(info.value.id).then(() => {
		uni.showToast({
			icon: 'none',
			title: '抢单成功'
		})
		info.value.status = 2
	})
}

/** 开始等待 或 开始服务 或 确认送达 */
function handlerUpdateOrderStatus (status, msg) {
	uni.showModal({
		title: '提示',
		content: `确定要${msg}吗？`,
		success: (res) => {
			if (res.confirm) {
				if (status === orderTypeEnum.PENDING_PAY.code) {
					// 如果是司机点击“完成订单”，那么传过来这个status就是待支付，需要司机选择用户的支付方式
					uni.showActionSheet({
						title: '请选择用户的支付方式',
						itemList: ['小程序线上支付', '扫码支付', '现金支付'],
						success: function (res) {
							finishOrder({ orderId: info.value.id, payType: res.tapIndex }).then(res => {
								uni.showToast({
									title: '操作成功',
									icon: 'none',
									success: () => {
										uni.reLaunch({
											url: '/pages/order/order'
										})
									}
								})
							})
						},
						fail: function (res) {
							console.log(res.errMsg);
						}
					});
				} else {
					// 其他操作，直接更新状态即可
					updateStatus({ id: info.value.id, status }).then(res => {
						info.value.status = status
						uni.showToast({
							icon: 'none',
							title: '操作成功'
						})
					})
				}
			}
		}
	})
	
}

/** 去起点或终点 */
function handlerGotoAddr (where) {
}

/** 页面挂载 */
onLoad(e => {
	const query = JSON.parse(e.query)
	info.value = query
	// 初始化位置
	getCurrLocation().then(() => {
		initMarkers()
		initPolyline()
	})
})

</script>

<style lang="scss" scoped>
view {
	box-sizing: border-box;
}
.container {
	width: 100vw;
	height: 100vh;
	
	// 地图 60%
	#map {
		width: 750rpx;
		height: 60%;
	}
	
	.box {
		width: 100%;
		bottom: 60rpx;
		height: calc(40% + 60rpx);
		position: relative;
		
		background-color: #fff;
		padding: 30rpx;
		z-index: 10;
		border-radius: 30rpx 30rpx 0 0;
		
		display: flex;
		flex-direction: column;
		
		.head {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.avatar {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				overflow: hidden;
				display: flex;
				align-items: center;
				justify-content: center;
				image {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}
			}
			.center {
				flex: 1;
				padding: 0 30rpx;
				.username {
					font-size: 32rpx;
					font-weight: 600;
					margin-bottom: 6rpx;
				}
				.xcx {
					font-size: 22rpx;
					color: #555;
				}
			}
			.call {
				
			}
		}
	
		.tags {
			display: flex;
			align-items: center;
			color: #555;
			font-size: 26rpx;
			padding: 20rpx 0;
			&>view {
				margin-right: 20rpx;
			}
			.price {
				font-size: 26rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				.num {
					font-size: 34rpx;
					font-weight: 600;
					color: #e00;
				}
			}
		}
		
		.from-and-to {
			.from, .to {
				width: 100%;
				margin-bottom: 20rpx;
				font-size: 28rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				
				.left {
					display: flex;
					align-items: center;
					justify-content: flex-start;
					
					.dot {
						width: 18rpx;
						height: 18rpx;
						border-radius: 50%;
						margin-right: 15rpx;
					}
					.green {
						background-color: #00b400;
					}
					.red {
						background-color: #d60000;
					}
					.text {
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
						width: 540rpx;
					}
				}
				
				.right {
					width: 100rpx;
					display: flex;
					align-items: center;
					justify-content: flex-end;
					color: #19afff;
				}
				
			}
			.from {
			}
			.to {
			}
		}
	
		.time {
			&>view {
				margin-bottom: 20rpx;
				font-size: 28rpx;
				// color: #555;
			}
		}
	
		.btn-contanier {
			background-color: #fff;
			flex: 1;
			display: flex;
			align-items: flex-end;
			justify-content: space-between;
			&>view {
				text-align: center;
				padding: 30rpx 0;
				border-radius: 15rpx;
				color: #fff;
				transition: all 0.3s ease;
			}
			.btn {
				width: 100%;
				background-color: #ffa50a;
				&:active {
					background-color: #ffc125;
				}
			}
			.btn-cancel {
				width: 40%;
				margin-right: 30rpx;
				background-color: #ffa50a;
				&:active {
					background-color: #ffc125;
				}
			}
			.btn-goto {
				flex: 1;
				background-color: #ffa50a;
				&:active {
					background-color: #ffc125;
				}
			}
		}
	}
}
</style>